package org.editor.servlet;

import com.google.gson.Gson;
import org.editor.entity.Blog;
import org.editor.util.HtmlUtils;
import org.editor.vo.Editor;
import org.editor.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * @Author zqx
 * @Date 2023-12-14
 */
@WebServlet("/blog/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        String content = req.getParameter("content");

        Blog blog = new Blog(title,author,content);
        String realPath = req.getServletContext().getRealPath("/");

        String templateFile = realPath  + "template/" + HtmlUtils.TEMPLATE_FILE;

        File f = new File(realPath + "blog/");
        if (!f.exists()) {
            f.mkdir();
        }
        String filename = new Random().nextInt() + ".html" ;
        String outputFile = realPath + "blog/" + filename;

        HtmlUtils.publish(blog,templateFile,outputFile);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        ResponseData responseData = new ResponseData();
        responseData.setErrno(0);
        responseData.setData("blog/" + filename);
        out.println(new Gson().toJson(responseData));
        out.flush();
        out.close();
    }
}
